<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">IOT设备集成平台</h3>
      <el-form-item v-if="tenantEnabled" prop="tenantId">
        <el-select v-model="loginForm.tenantId" filterable remote :remote-method="remoteMethod" :loading="loading"
          placeholder="请选择/输入公司名称" style="width: 100%">
          <el-option v-for="item in options" :key="item.tenantId" :label="item.companyName"
            :value="item.tenantId"></el-option>
          <!-- <template slot="prefix"></template> -->
        </el-select>
        <!-- <el-input v-model="loginForm.username" type="text" size="large" autocomplete="off" placeholder="账号">
          <template slot="prefix"><i class="el-icon-s-shop"></i></template>
        </el-input> -->
      </el-form-item>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" size="large" autocomplete="off" placeholder="账号">
          <template slot="prefix"><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" size="large" autocomplete="off" placeholder="密码"
          @keyup.enter="handleLogin" show-password>
          <template slot="prefix"><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item v-if="captchaEnabled" prop="code">
        <el-input v-model="loginForm.code" size="large" autocomplete="off" placeholder="验证码" style="width: 63%"
          @keyup.enter="handleLogin">
          <template slot="prefix"><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" class="login-code-img" @click="getCode" />
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">记住密码</el-checkbox>
      <!-- <el-form-item style="float: right">
        <el-button circle title="微信登录" @click="doSocialLogin('wechat')">
          <svg-icon icon-class="wechat" />
        </el-button>
        <el-button circle title="MaxKey登录" @click="doSocialLogin('maxkey')">
          <svg-icon icon-class="maxkey" />
        </el-button>
        <el-button circle title="TopIam登录" @click="doSocialLogin('topiam')">
          <svg-icon icon-class="topiam" />
        </el-button>
        <el-button circle title="Gitee登录" @click="doSocialLogin('gitee')">
          <svg-icon icon-class="gitee" />
        </el-button>
        <el-button circle title="Github登录" @click="doSocialLogin('github')">
          <svg-icon icon-class="github" />
        </el-button>
      </el-form-item> -->
      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div v-if="register" style="float: right">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import { ref, reactive, watch, onMounted } from 'vue';
// import { useRouter } from 'vue-router';
import { getCodeImg, getTenantList } from '@/api/login';
import { authBinding } from '@/api/system/auth';
import { to } from 'await-to-js';
// import { useUserStore } from '@/store/modules/user';
import { HttpStatus } from '@/enums/RespEnum';

export default {
  data() {
    return {
      loginForm: {
        tenantId: '',
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: ''
      },
      uuid: "",
      loginRules: {
        tenantId: [{ required: true, trigger: 'blur', message: '请输入您的租户编号' }],
        username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
        password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
        code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
      },
      codeUrl: '',
      loading: false,
      captchaEnabled: true,
      tenantEnabled: true,
      register: false,
      redirect: undefined,
      tenantList: [],
      list: [],
      options: []
    };
  },
  components: {
    // Your component imports here
  },
  methods: {
    handleLogin() {
      this.$refs.loginRef.validate(async (valid, fields) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            localStorage.setItem('clientId', String(this.loginForm.tenantId));
            localStorage.setItem('username', String(this.loginForm.username));
            localStorage.setItem('password', String(this.loginForm.password));
            localStorage.setItem('rememberMe', String(this.loginForm.rememberMe));
          } else {
            localStorage.removeItem('clientId');
            localStorage.removeItem('username');
            localStorage.removeItem('password');
            localStorage.removeItem('rememberMe');
          }
          
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || "/" }).catch(() => { });
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        } else {
          console.log('error submit!', fields);
        }
      });
    },
    getCode() {
      getCodeImg({}).then((res) => {
        this.captchaEnabled = res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.data.img;
          this.$set(this.loginForm, 'uuid', res.data.uuid);
          this.uuid = res.data.uuid
          localStorage.setItem("uuid", this.uuid)
        }
      });
    },
    async getLoginData() {
      const tenantId = localStorage.getItem('tenantId');
      if (tenantId) {
        this.options = this.tenantList.filter(item => {
          return item.tenantId == tenantId;
        });
      }
      const username = localStorage.getItem('username');
      const password = localStorage.getItem('password');
      const rememberMe = localStorage.getItem('rememberMe');
      this.loginForm = {
        tenantId: tenantId === null ? String(this.loginForm.tenantId) : tenantId,
        username: username === null ? String(this.loginForm.username) : username,
        password: password === null ? String(this.loginForm.password) : String(password),
        rememberMe: rememberMe === null ? false : Boolean(rememberMe)
      };
    },
    async initTenantList() {
      const { data } = await getTenantList();
      this.tenantEnabled = data.tenantEnabled === undefined ? true : data.tenantEnabled;
      if (this.tenantEnabled) {
        this.tenantList = data.voList;
        if (this.tenantList != null && this.tenantList.length !== 0) {
          // this.loginForm.tenantId = this.tenantList[0].tenantId;
        }
        this.getLoginData();

        // this.list = this.tenantList.map(item => {
        //   return { value: `value:${item}`, label: `label:${item}` };
        // });
      }
    },
    doSocialLogin(type) {
      authBinding(type, this.loginForm.tenantId).then((res) => {
        if (res.code === HttpStatus.SUCCESS) {
          window.location.href = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    remoteMethod(query) {
      this.options = []
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.options = this.tenantList.filter(item => {
            console.log(item)
            console.log(query)
            return item.companyName == query;
          });
          // console.log(options)
          // this.options.push(options)
        }, 200);
      } else {
        this.options = [];
      }
    }
  },
  watch: {
    '$route'(newRoute) {
      this.redirect = newRoute.query && newRoute.query.redirect;
    }
  },
  mounted() {
    this.getCode();
    this.initTenantList();
  }
};
</script>

<style scoped lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url('../assets/images/login-background.jpg');
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
